package com.powervision.base.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.powervision.http.entity.ApiResponse
import com.jeremyliao.liveeventbus.LiveEventBus
import com.powervision.http.LOADING_STATE
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 * @auth: njb
 * @date: 2021/11/12 10:27
 * @desc: 路由中心
 */
abstract class BaseViewModel : ViewModel() {


    protected fun showLoadingV2() {
        LiveEventBus.get<Boolean>(LOADING_STATE).post(true)
    }

    protected fun stopLoadingV2() {
        LiveEventBus.get<Boolean>(LOADING_STATE).post(false)
    }

    protected fun <T> launchWithLoading(
        requestBlock: suspend () -> ApiResponse<T>,
        resultCallback: (ApiResponse<T>) -> Unit
    ) {
        viewModelScope.launch {
            flow {
                emit(requestBlock.invoke())
            }.onStart {
                showLoadingV2()
            }.onCompletion {
                stopLoadingV2()
            }.collect {
                resultCallback(it)
            }
        }
    }

}